package com.hpx.javaeye.screen;

import net.rim.device.api.i18n.ResourceBundle;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.component.PasswordEditField;
import net.rim.device.api.ui.container.MainScreen;

import com.hpx.chinastore.resource.JavaEyeResource;
import com.hpx.javaeye.JavaEye;
import com.hpx.javaeye.model.User;
import com.hpx.javaeye.util.Authentication;

public class LoginScreen extends MainScreen implements JavaEyeResource {

	private static ResourceBundle _resource = ResourceBundle.getBundle(
			BUNDLE_ID, BUNDLE_NAME);
	private MenuItem _loginMenu;
	private EditField logid;
	private PasswordEditField pwd;

	public boolean onClose() {

		return super.onClose();
	}

	public LoginScreen() {
		uiManage();
	}

	private void uiManage() {
		_loginMenu = new MenuItem(_resource, MENUITEM_LOGIN, 200000, 10) {
			public void run() {
				onLogin();
			}
		};

		logid = new EditField("User Name:", "huangpengxiao", 20, FIELD_TOP
				| FIELD_LEFT);
		pwd = new PasswordEditField("User Password:", "830304", 20, FIELD_TOP
				| FIELD_LEFT);
		add(logid);
		add(pwd);
	}

	private MenuItem _close = new MenuItem("Close", 110, 10) {
		public void run() {
			System.exit(0);
		}
	};

	protected void makeMenu(Menu menu, int index) {
		menu.add(_close);
		menu.add(_loginMenu);
	}

	private void onLogin() {
		String url = _resource.getString(VERIFY_URL/* TEST_URL */);
		String username = logid.getText();
		String password = pwd.getText();

		Authentication ac = new Authentication() {
			public void process(byte[] b) {
				System.out.println(new String(b));

				User user = new User().extractFromJson(new String(b));
				System.out.println(user);

				JavaEye j = (JavaEye) UiApplication.getUiApplication();

				j.setUser(user);

				ListScreen screen = new ListScreen();

				j.pushScreen(screen);

			}

			public void process(byte b) {
			}

			public void processType(String type) {
			}
		};
		ac.passHttpBasic(url, username, password);
	}
}
